package com.hive;
import java.sql.*;

public class HiveDBUtil {
	private HiveDBUtil() {}
	private static String url = "jdbc:hive2://master:10000/default";
	private static String userName = "root";
	private static String password = "root";
	
	static {
		try {
			Class.forName("org.apache.hive.jdbc.HiveDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public static int update(String sql) {
		Connection conn=null;
		Statement stm=null;
		
		try {
			conn=getConn();
			stm=conn.createStatement(); 
			return stm.executeUpdate(sql);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally {
			close(null,stm,conn);
		}	
	}
	
	public static Connection getConn() {
		try {
			return DriverManager.getConnection(url, userName, password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public static void close(ResultSet rs , Statement stm,Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (stm != null) {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	static void test1() throws Exception {
		Connection conn =HiveDBUtil.getConn();
		//创建数据传输对象
		Statement stm = conn.createStatement();

		//执行查询
		String sql = "select * from people ";
		ResultSet rs = stm.executeQuery(sql);

		//从结果集中取出结果
		while (rs.next()) {
			System.out.print(rs.getString("id") + "  ");
			System.out.print(rs.getString("peoplename") + "  ");
			System.out.print(rs.getInt("age") + " ");
			System.out.println(rs.getString("countryname"));
		}

		HiveDBUtil.close(rs,stm,conn);
	}
	
	static void test3() {
		HiveDBUtil.update("create table cat( id int, catName String)");
		System.out.println("ok");	
	}
	
}
